import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class AddressBookConsole {

  private static AddressBook addressBook = new AddressBook();
  private static ArrayList<Contact> contacts = addressBook.getContacts();

  /**
   * name是否已经存在于通讯录AddressBook中
   *
   * @param name
   * @return
   */
  private static boolean isNameExist(String name) {
    ArrayList<Contact> contacts = addressBook.getContacts();
    if (contacts == null) {
      return false;
    }

    for (Contact contact : contacts) {
      if (contact.getName().equals(name)) {
        return true;
      }
    }
    return false;
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) throws IOException {
    Scanner sca = new Scanner(System.in);
    String command;
    boolean bQuitting = false;

    do {
      String mainPrompt = "";
      mainPrompt += "\n-------------------------------------------------------------------------------------------------------------------\n";
      mainPrompt += ("Addressbook file: SHOW THE PATH OF THE LOADED FILE HERE\n");
//      mainPrompt += "n – create a new address book\n";
      mainPrompt += "l <filename> - load an address book from the specified file\n";
//      mainPrompt += "s - save the current address book\n";
      mainPrompt += "v <filename> - save the current address book into the specified file\n";
      mainPrompt += "a <name>;<email>;<telephone>;<street>;<city>;<zip>;<country> - add a new contact to the address book. \n";
      mainPrompt += "d <name> - delete the specified contact\n";
      mainPrompt += "p <name prefix> - show contacts whose names start with the given prefix\n";
      mainPrompt += "o – show all the contacts in the current address book\n";
      mainPrompt += "q quit the applicaiton\n";
      mainPrompt += "-------------------------------------------------------------------------------------------------------------------\n";

      System.out.print(mainPrompt);
      command = sca.nextLine();
      String params = command.substring(1).trim();
      if (contacts == null) {
        contacts = new ArrayList<>();
      }
      switch (command.charAt(0)) {
//        case 'n':
//          addressBook = new AddressBook();
//          System.out.println("New addressbook created.");
//          break;
        case 'l':
          //Do something here. In addition, you need to parse the command to get the input filename too! The same for v, a, d, and p.
          List<Contact> contactList = new ArrayList<>();
          int status = CSVUtils.load(params, contactList);
          if (status == -1) {
            throw new IOException("file error!");
          }
          contacts.addAll(contactList);
          System.out.printf("File %s loaded.", params.substring(params.lastIndexOf("\\") + 1));
          System.out.println();
          System.out.println("=====================================");

          if (contactList.size() == 0) {
            System.out.println("no data!");
          } else {
            for (Contact contact : contactList) {
              System.out.println("name: " + contact.getName());
              System.out.println("email: " + contact.getEmail());
              System.out.println("phone: " + contact.getPhone());
              System.out.println("street: " + contact.getStreet());
              System.out.println("city: " + contact.getCity());
              System.out.println("zip: " + contact.getZip());
              System.out.println("country: " + contact.getCountry());
              System.out.println("=====================================");
            }
          }
          break;
//        case 's':
//          //Do something here.
//          System.out.println("File saved successfully.");
//          break;
        case 'v':
          int status2 = CSVUtils.saveAs(params, contacts);
          if (status2 == -1) {
            throw new IOException("file error!");
          }
          System.out.printf("File saved as %s.", params.substring(params.lastIndexOf("\\") + 1));
          break;
        case 'a':
          boolean flag = isNameExist(params.split(";")[0]);
          if (flag) {
            System.out.println("error: name duplicate!");
            break;
          }

          Contact contact = Contact.formatContact(params);
          contacts.add(contact);
          addressBook.setContacts(contacts);
          System.out.println("New contact added.");
          break;
        case 'd':
          if (contacts.size() == 0) {
            System.out.println("error: empty contacts!");
            break;
          }

          Iterator<Contact> it = contacts.iterator();
          boolean isRemoved = false;
          while (it.hasNext()) {
            Contact contact1 = it.next();
            if (contact1.getName().equals(params)) {
              it.remove();
              isRemoved = true;
              System.out.println("1 contact deleted.");
              break;
            }
          }

          if (!isRemoved) {
            System.out.println("error: no contact");
            break;
          }
          break;
        case 'p':
          if (contacts.size() == 0) {
            System.out.println("error: empty contacts!");
            break;
          }

          Iterator<Contact> iterator = contacts.iterator();
          boolean isDataShow = false;
          while (iterator.hasNext()) {
            Contact contact1 = iterator.next();
            if (contact1.getName().contains(params)) {
              System.out.println("name: " + contact1.getName());
              System.out.println("email: " + contact1.getEmail());
              System.out.println("phone: " + contact1.getPhone());
              System.out.println("street: " + contact1.getStreet());
              System.out.println("city: " + contact1.getCity());
              System.out.println("zip: " + contact1.getZip());
              System.out.println("country: " + contact1.getCountry());
              System.out.println("=====================================");
              isDataShow = true;
            }
          }

          if (!isDataShow) {
            System.out.println("no data!");
          }
          break;
        case 'o':
          if (contacts.size() == 0) {
            System.out.println("error: empty contacts!");
            break;
          }

          for (Contact contact1 : contacts) {
            System.out.println("name: " + contact1.getName());
            System.out.println("email: " + contact1.getEmail());
            System.out.println("phone: " + contact1.getPhone());
            System.out.println("street: " + contact1.getStreet());
            System.out.println("city: " + contact1.getCity());
            System.out.println("zip: " + contact1.getZip());
            System.out.println("country: " + contact1.getCountry());
            System.out.println("=====================================");
          }
          break;
        case 'r':
          //命令格式：r <filename> <customer name>
          String filename = params.split(" ")[0];
          String customerName = params.split(" ")[1];
          List<Order> orderList = new ArrayList<>();
          int status1 = CSVUtils.loadOrder(filename, orderList);
          if (status1 == -1) {
            throw new IOException("file error!");
          }

          Iterator<Order> orderIt = orderList.iterator();
          while (orderIt.hasNext()) {
            Order order = orderIt.next();
            if (!order.getCustomerName().equals(customerName)) {
              orderIt.remove();
            }
          }

          if (orderList.size() == 0) {
            System.out.println("no data!");
          } else {
            for (Order order : orderList) {
              System.out.println("id: " + order.getOrderID());
              System.out.println("Customer Name: " + order.getCustomerName());
              System.out.println("Product Name: " + order.getProductName());
              System.out.println("Quantity: " + order.getQuantity());
              System.out.println("=====================================");
            }
          }
          break;
        case 'q':
          //Do something here.
          //Perhaps you may request the user to confirm if not saved yet.
          bQuitting = true;
          break;
        default:
          System.out.println("Invalid input!");
      }
      //pressAnyKeyToContinue();
    } while (!bQuitting);
    System.out.println("Thanks for using, goodbye!");
  }
}
